package com.yj.common.utils;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yj.common.core.domain.entity.Member;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WechatUtil {

    // 小程序ID
    private static final String appid = "wxc13e24a00e4e674c";
    // 小程序密钥
    private static final String secret = "fa1126cf0aded51c5790154aeaf4fa6a";

    // 自己测试的小程序
//    private static final String appid = "wx53c609c8279b85c3";
//    private static final String secret = "5072ed6c826ad582f493c8f66be57af0";

    public static JSONObject getSessionKeyOrOpenId(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<>();
        // https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
        //小程序appId
        requestUrlParam.put("appid", appid);
        //小程序secret
        requestUrlParam.put("secret", secret);
        //小程序端返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");
        //发送post请求读取调用微信接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
        return jsonObject;
    }

    /**
     * 微信小程序加密数据解密：用于getUserInfo、getPhoneNumber
     *
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return
     * @throws Exception
     */
    public static JSONObject wXBizDataCrypt(String encryptedData, String sessionKey, String iv) {

        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.这个if中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            log.error("解密加密信息报错" + e.getMessage(), e);
        }
        return null;
    }

    public static boolean hasDiff(Member member, JSONObject rawDataJson) {
        String nickName = rawDataJson.getString("nickName");
        if (!(nickName == member.getNickName() || (nickName != null && nickName.equals(member.getNickName())))) {
            return true;
        }
//        String avatarUrl = rawDataJson.getString("avatarUrl");
//        if (!(avatarUrl == member.getAvatarUrl() || (avatarUrl != null && avatarUrl.equals(member.getAvatarUrl())))) {
//            return true;
//        }
        return false;
    }
}
